package com.ynny.Dao.Impl;

import com.ynny.Dao.UsersDao;
import com.ynny.Entity.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class UsersDaoImpl implements UsersDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public Users findUserByName(String number) {
        String sql = "select * from users where number = ?";
        List<Users> users = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Users.class), number);
        return users.isEmpty() ? null : users.get(0);
    }

    @Override
    public int addUser(Users user) {
        String sql = "insert into users(number,password,identity,sex) values(?,?,?,?)";
        return jdbcTemplate.update(sql,user.getNumber(),user.getPassword(),user.getIdentity(),user.getSex());
    }

    @Override
    public boolean existsByNumber(String number) {
        String sql = "select count(*) from users where number = ?";
        Integer count = jdbcTemplate.queryForObject(sql, Integer.class, number);
        return count > 0;
    }
}
